package com.WISSC.interceptor;

import com.WISSC.bean.*;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by Zhang on 2018/8/26.
 */
public class Sessioninterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        HttpSession session = request.getSession();
        int interval = session.getMaxInactiveInterval();
        User user=(User) session.getAttribute("user");
        System.out.println("访问路径:::"+request.getServletPath());



        if(request.getServletPath().equals("/")){
            return  true;
        }
        if (session.getAttribute("user") != null){

            return true;
        } else {
            if(request.getServletPath().equals("/file/uploadFile")){
                if(session.getAttribute("user") == null){
                    response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);

                    response.getWriter().write("{" +
                            "  \"code\": -1" +
                            "  ,\"msg\": \"登录已失效\"" +
                            "  ,\"data\": {" +
                            "    \"src\": \"\"" +
                            "  }" +
                            "}       ");
                    response.getWriter().flush();
                    return  false;
                }
            }
            System.err.println("来了");
            redirect(request,response);
            //response.sendRedirect("http://localhost/user/login.html");
            return false;
        }






    }





    //对于请求是ajax请求重定向问题的处理方法
    public void redirect(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取当前请求的路径
        //String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName()+ ":" + request.getServerPort() + request.getContextPath();
        System.out.println("basePath:"+basePath);
        // 如果request.getHeader("X-Requested-With") 返回的是"XMLHttpRequest"说明就是ajax请求，需要特殊处理 否则直接重定向就可以了
        if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
            //告诉ajax我是重定向
            response.setHeader("REDIRECT", "REDIRECT");
            // 告诉ajax我重定向的路径
            response.setHeader("CONTENTPATH", basePath + "/user/login.html");
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        } else {
            response.sendRedirect(basePath + "/user/login.html");
        }

    }




}

